import React, { Component } from "react";
import { Modal, Form, Input, Spin } from "antd";
const FormItem = Form.Item;

@Form.create()
export default class AdminEditForm extends Component {
  constructor(props) {
    super(props);
    const { record } = props;
    this.state = {
      formDatas: {
        id: "",
        name: "",
        remark: "",
        ...record
      }
    };
  }
  /**
   * 返回表单数据到父组件
   */
  onOk = () => {
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.props.onOk(values);
      }
    });
  };
  /**
   * 清除表单数据
   */
  handleFormClear = () => {
    const { form } = this.props;
    form.resetFields();
  };

  render() {
    const { modalType, loading = false, record, form } = this.props;
    const { getFieldDecorator } = form;
    let { formDatas } = this.state;
    formDatas = { formDatas, ...record };
    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 16 }
    };
    return (
      <Modal
        visible={this.props.visible}
        title={`${modalType !== "edit" ? "新增" : "编辑"}角色`}
        okText="提交"
        cancelText="取消"
        onCancel={this.props.onCancel}
        onOk={this.onOk}
        afterClose={this.handleFormClear}
      >
        <Spin tip="数据加载中..." spinning={loading}>
          <Form>
            <FormItem {...formItemLayout} label="角色名称" hasFeedback>
              {getFieldDecorator("name", {
                initialValue: formDatas.name,
                rules: [{ required: true, message: "请输入角色名称！" }]
              })(<Input />)}
            </FormItem>
            <FormItem {...formItemLayout} label="角色描述" hasFeedback>
              {getFieldDecorator("remark", {
                initialValue: formDatas.remark,
                rules: [{ required: false, message: "请输入角色描述！" }]
              })(<Input />)}
            </FormItem>
          </Form>
        </Spin>
      </Modal>
    );
  }
}
